package com.doudou.base.resources.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * mybatisplus自定义填充公共字段 ,即没有传的字段自动填充
 * @author anyp
 * @date 2019-05-29
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    private static String CREATE_TIME = "createDate";
    private static String UPDATE_TIME = "updateDate";
    private static String DEL_FLAG = "delFlag";
    /**
     * 新增填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createTime = metaObject.getValue(CREATE_TIME);
        Object updateTime = metaObject.getValue(UPDATE_TIME);
        Object delFlag = metaObject.getValue(DEL_FLAG);
        if (null == createTime) {
            metaObject.setValue(CREATE_TIME, new Date());
        }
        if (null == updateTime) {
            metaObject.setValue(UPDATE_TIME, new Date());
        }
        if (null == delFlag) {
            metaObject.setValue(DEL_FLAG, 0);
        }
    }

    /**
     * 新增填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateTime = null;
        if(metaObject.hasGetter(UPDATE_TIME)){
            updateTime = metaObject.getValue(UPDATE_TIME);
        }
        if (null == updateTime) {
            metaObject.setValue(UPDATE_TIME, new Date());
        }
    }}
